package com.dkm.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.dkm.entity.SignInLog;
import com.dkm.repository.SignInLogRepository;
import com.dkm.service.SignInLogService;

@Service
public class SignInLogServiceImpl implements SignInLogService {

	//注入签到日志持久层
	@Autowired
	private SignInLogRepository signInLogRepository;
	
	@Override
	public SignInLog getSignInLogByUser_idAndDate(String user_id,Date begin_time,Date end_time) {
		
		return signInLogRepository.getSignInLogByUser_idAndDate(user_id, begin_time,end_time);
	}

	@Override
	public Page<SignInLog> findAllSignInLogs(Map<String,Object> map, Pageable pageable) {
		// TODO Auto-generated method stub
		return signInLogRepository.findAll(this.get(map), pageable);
	}

	private Specification<SignInLog> get(Map<String,Object> map) {
		
		return new Specification<SignInLog>() {

			@Override
			public Predicate toPredicate(Root<SignInLog> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				//1、创建Predicate对象,动态sql表达式
				Predicate predicate=criteriaBuilder.conjunction();
				//2、创建一个集合，存放多个条件,动态sql表达式集合
				List<Expression<Boolean>> expressions=predicate.getExpressions();
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				SignInLog signInLog=(SignInLog) map.get("signInLog");
				
				//用户名
				if(!StringUtils.isEmpty(signInLog.getUser_name())) {
					expressions.add(criteriaBuilder.like(root.get("user_name"), "%"+signInLog.getUser_name()+"%"));
				}
				//签到时间
				try {
					if(!StringUtils.isEmpty(map.get("beginDate"))) {
						expressions.add(criteriaBuilder.greaterThanOrEqualTo(root.get("sign_in_time"), sdf.parse(map.get("beginDate").toString())));
					}
					if(!StringUtils.isEmpty(map.get("endDate"))) {
						expressions.add(criteriaBuilder.lessThanOrEqualTo(root.get("sign_in_time"), sdf.parse(map.get("endDate").toString())));
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//签到状态
				if(signInLog.getSign_in_status()!=null) {
					expressions.add(criteriaBuilder.equal(root.get("sign_in_status"), signInLog.getSign_in_status()));
				}
				
				return predicate;
			}
		};
	}

}
